package handler

import (
	"encoding/json"
	"github.com/sirupsen/logrus"
	"gofile/src/config"
	"gofile/src/util"
	"io"
	"net/http"
	"os"
	"strings"
)

type FileListReq struct {
	Path string `json:"path"`
}
type FileListItem struct {
	Id       string `json:"id"`
	Name     string `json:"name"`
	IsParent bool   `json:"isParent"`
	PId      string `json:"pId"`
	Url      string `json:"url"`
	Size     int64  `json:"size"`
}

func convert(f os.DirEntry, dirPath string, rootDir string, myCfg config.Config) FileListItem {

	pId := strings.Replace(dirPath, rootDir, "", -1)
	var id string
	if strings.HasSuffix(dirPath, "/") {
		id = strings.Replace(dirPath+f.Name(), rootDir, "", -1)
	} else {
		id = strings.Replace(dirPath+"/"+f.Name(), rootDir, "", -1)
	}
	url := myCfg.File.BaseUrl + id
	info, _ := f.Info()

	return FileListItem{Id: id, Name: f.Name(), IsParent: f.IsDir(), PId: pId, Url: url, Size: info.Size()}
}
func FileListHandler(w http.ResponseWriter, r *http.Request) {
	myCfg := config.GetConfig()

	rootDir := myCfg.File.Dir
	logrus.Infoln(myCfg.File.Dir)
	body, _ := io.ReadAll(r.Body)
	logrus.Infoln(body)
	var fileListReq FileListReq
	err := json.Unmarshal(body, &fileListReq)
	if err != nil {
		util.ProcessResult("参数错误", err, w)
		return
	}
	logrus.Infoln(fileListReq.Path)

	path := fileListReq.Path
	dirPath := rootDir
	if path == "" {
		dirPath = rootDir

	} else {
		dirPath = rootDir + path
	}
	files, err := os.ReadDir(dirPath)
	if err != nil {
		util.ProcessResult("参数错误", err, w)
		return
	}

	var fileItems []FileListItem
	for _, f := range files {
		if f.IsDir() {
			fileItems = append(fileItems, convert(f, dirPath, rootDir, myCfg))
		}
	}
	for _, f := range files {
		if !f.IsDir() {
			fileItems = append(fileItems, convert(f, dirPath, rootDir, myCfg))
		}
	}
	util.ProcessResult(fileItems, nil, w)
}
